package com.unism.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebExcelHandler {
	/**
	 * 用来将需要到处的结果集生成excel输出到用户端
	 * @param resultList
	 * @param name
	 * @param clazz
	 * @param req
	 * @param res
	 * @return
	 */
	public static String exportQueryToExcel(List resultList,String name,Class clazz,HttpServletResponse res,HttpServletRequest req) {
		
        String rootpath = req.getSession().getServletContext().getRealPath(
                "/")
                + File.separatorChar + "download" + File.separatorChar; // 路径
        name = name+".xls";// 文件名
        String fileName = ExcelExportHelper.Export(resultList, rootpath, name,
                clazz);
        res.reset();// 清空输出流
        res.setCharacterEncoding("utf-8");
        // 输出字节流
        try {
        	String downLoadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            // 设定输出文件头
        	res.setHeader(
                    "Content-disposition",
                    "attachment; filename="
                            + new String(downLoadFileName));
            // 定义输出类型
        	res.setContentType("application/msexcel");
            InputStream in = new FileInputStream(rootpath + fileName);
            int n = 1024;
            byte buffer[] = new byte[n];
            while ((in.read(buffer, 0, n) != -1) && (n > 0)) {
            	res.getOutputStream().write(buffer);
            }
            File f = new File(rootpath + fileName);
            if(f.exists()){
            	f.delete();	
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
